import { createRouter, createWebHistory, createWebHashHistory } from "vue-router"
import { check_token } from "../api/user"
import { user_Store } from "@/store/user"
import { websocket_start } from "../static/js/socket/login.js"
import index_router from "./index.js"
import community_router  from "./community.js"
import admin_router from "./Admin.js"
import myself_router from "./myself.js"
import render_router from "./render.js"
import test_router from "./test.js"
import chat_router from"./chat.js"


// 为了减少routerview的使用
const new_Router = index_router
    .concat(community_router )
    .concat(admin_router)
    .concat(myself_router)
    .concat(render_router)
    .concat(test_router)
    .concat(chat_router)
const ROUTER = createRouter({
    history: createWebHistory(),
    routes: new_Router,
    // baseUrl:"/"
    }
)

ROUTER.beforeEach(async (to, from, next) => {
    // console.log(to.path, from.path)
    // console.log(to.meta)
    // 如果路由不需要登录，直接放行
    const user = user_Store();
    try { 
        if (user.get_user()?.id != undefined && !user.get_user_life_data()&& user.get_user()?.id != null) {
            websocket_start(user.get_user().id);
            user.set_user_isfirstlogin(false)
        }
    } catch (error) {
        
    }
    if (!to.meta.requiresAuth) {
        next();
        return;
    }
  
    
    const judge = await check_token();
    if (judge == 0 || judge == 401 || judge == 404) {
        // 跳转到不需要登录的路由（如登录页）
        next({ name: 'index' });
        return
    } else if (judge.status == 'valid') {
        
        // 如果是第一次登录，启动 WebSocket
        if (!user.get_user()) {
                user.set_user_info(judge.user);
        } 
        if (user.get_user_isfirstlogin()) { 
            websocket_start(user.get_user().id);
            user.set_user_isfirstlogin(false)
        }
            //token 有效，设置用户信息.
            // 如果需要权限
            if (to.meta.permission) {
                if (judge.user.admin == 'valid') {
                    next()
                    return
                }
                else {
                    next({ name: "index" })
                    return
                }
            
            }
            next()
            return
        } else {
            // 处理其他异常
        next({name:"index"})
        }
    
}


)

export default ROUTER
